#include <51func.h>
#define NUM 10000000
#define wants_to_enter0 p[1]
#define wants_to_enter1 p[2]
#define turn p[3]
int main(int argc, char *argv[])
{
    // 创建物理内存
    int shmid = shmget(IPC_PRIVATE,4096,IPC_CREAT|0600);
    // IPC_PRIVATE-->0 私有共享内存 用于父子进程间数据通信
    // 申请虚拟内存
    int *p = (int *)shmat(shmid,NULL,0);
    p[0] = 0;

    wants_to_enter0 = 0;
    wants_to_enter1 = 1;
    turn =  0;

    if(fork()){
        for(int i = 0; i < NUM; ++i){
            wants_to_enter0 = 1;
            while(wants_to_enter1){
                if(turn != 0){
                    wants_to_enter0 = 0;
                    while(turn != 0) {}
                    wants_to_enter0 = 1;
                }
            }// 加锁
            ++p[0];
            // 解锁
            turn = 1;
            wants_to_enter0 = 0;
        }
        wait(NULL);
        printf("total = %d\n", p[0]);
    }
    else{
        for(int i = 0; i < NUM; ++i){
            wants_to_enter1 = 1;
            while(wants_to_enter0){
                if(turn != 1) {
                    wants_to_enter1 = 0;
                    while(turn != 1) {}
                    wants_to_enter1 = 1;
                }
            }
            ++p[0];
            turn = 0;
            wants_to_enter1 = 0;
        }

    }
    return 0;
}

